package com.enzoism.manual.springboot.controller;

import com.enzoism.manual.springboot.model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IndexController {

    /***
     * 测试接口
     * @return
     */
    @GetMapping("hello")
    public String index(){
        return "Hello,SpringBoot!";
    }

    /**
     * 默认试图跳转
     * @param model
     * @return
     */
    @RequestMapping({"/","/index","/index.html"})
    public String toIndex(Model model){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String userName = null==user?"xiaoming":user.getName();
        model.addAttribute("msg","hello,"+userName);
        return "index";
    }

    /**
     * 跳转登录页面
     * @return
     */
    @RequestMapping(value = {"/toLogin"})
    public String usrLogin(){
        return "login";
    }

    /***
     * 没有权限的报错提醒，当前直接将文字渲染在页面上
     * @return
     */
    @RequestMapping(value = {"/noauth"})
    @ResponseBody
    public String noAuth(){
        return "未经授权无法访问";
    }

    @RequestMapping(value = {"/login"})
    public String usrLoginIn(String username, String password, Model model) {
        System.out.println("------用户点击登录操作，进行权限判断："+username+password);
        // 1、获取当前用户
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login( token );
            // 如果没有问题，那就对了，搞定！-并回显用户登录姓名
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            String userName = null==user?"xiaoming":user.getName();
            model.addAttribute("msg","hello,"+userName);
            return "index";
        } catch ( UnknownAccountException uae ) {
            // 未知用户的帐号，告诉他们错误信息？
            model.addAttribute("msg","未知用户的帐号");
            return "login";
        } catch ( IncorrectCredentialsException ice ) {
            // 密码不匹配，重试？
            model.addAttribute("msg","密码不匹配");
            return "login";
        } catch ( LockedAccountException lae ) {
            // 该帐号被锁定了，无法登录。给他们显示一条信息？
            model.addAttribute("msg","该帐号被锁定了");
            return "login";
        } catch (AuthenticationException ae ) {
            model.addAttribute("msg","请在doGetAuthorizationInfo方法中完成授权操作");
            return "login";
        }
    }
    //------------------------------权限拦截------------------------------//

    @RequestMapping({"/user/add"})
    public String userAdd(){
        return "user/add";
    }

    @RequestMapping(value = {"/user/edit"})
    public String userEditor(){
        return "user/edit";
    }
}
